package com.fate.system.utils;

import com.fate.system.enums.PictureSizeEnum;
import com.fate.system.vo.tencent.FormatImageVO;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Slf4j
public class FillPicture {
  /**
   * 填充图片
   *
   * @param base64 base64
   * @param color 颜色
   * @return
   */
  public static FormatImageVO fillPicture(String base64, Color color, PictureSizeEnum photoSize) {
    // 读取ResultImage图片
    BufferedImage resultImage = FillPicture.decodeToImage(base64);
    // 创建一个蓝色背景的图像
    BufferedImage finalImage =
        new BufferedImage(
            resultImage.getWidth(), resultImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = finalImage.createGraphics();

    // 填充蓝色背景
    g.setColor(color);
    g.fillRect(0, 0, finalImage.getWidth(), finalImage.getHeight());

    // 将ResultImage叠加到蓝色背景上
    g.drawImage(resultImage, 0, 0, null);
    g.dispose();

    BufferedImage resized1Inch = ImageCropper.cropAndResizeImage(finalImage, photoSize);

    return new FormatImageVO(
        FillPicture.encodeToString(resized1Inch, "png"),
        photoSize.getWidthPx(),
        photoSize.getHeightPx(),
        null,
        null,
        null);
  }

  /**
   * 将Base64字符串转换为BufferedImage
   *
   * @param base64Image base64
   * @return BufferedImage
   */
  public static BufferedImage decodeToImage(String base64Image) {
    BufferedImage image = null;
    try {
      // 将Base64字符串解码为字节数组
      byte[] imageBytes = Base64.getDecoder().decode(base64Image);

      // 将字节数组转换为BufferedImage
      ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
      image = ImageIO.read(bis);
      bis.close();
    } catch (IOException e) {
      log.error("Error decoding image: {}", e.getMessage());
    }
    return image;
  }

  /**
   * 将BufferedImage转换为Base64字符串
   *
   * @param image BufferedImage
   * @param format 图片格式
   * @return base64
   */
  public static String encodeToString(BufferedImage image, String format) {
    String base64Image = null;
    try {
      // 创建一个字节数组输出流
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      // 将BufferedImage写入到字节数组输出流中
      ImageIO.write(image, format, bos);

      // 将字节数组编码为Base64字符串
      byte[] imageBytes = bos.toByteArray();
      base64Image = Base64.getEncoder().encodeToString(imageBytes);

      // 关闭字节数组输出流
      bos.close();
    } catch (IOException e) {
      log.error("Error encoding image: {}", e.getMessage());
    }
    return base64Image;
  }
}
